import { postLogin } from '@/api/user'
import router from '@/router'
import { resetRouter } from '@/router'
import { getToken, setToken, removeToken, setUserName, getUserName } from '@/utils/auth'
// import { Message } from 'element-ui'

// 声明数据
const state = {

  token: getToken(),
  userMenus: null,
  user: {},
  name: getUserName(),
  avatar: ''
}
// 修改state数据的方法
const mutations = {
  setToken(state, token) {
    state.token = token
  },
  setUserInfo(state, { user, name, avatar }) {
    state.user = user
    state.name = name
    state.avatar = avatar
  }

  // mutationsUserMenus(state, payload) {
  //   state.avatar = payload
  // }

}
// 发请求
const actions = {
  async login(context, payload) {
    // 登录请求
    const res = await postLogin(payload)
    // 提示用户
    // Message.success(res.data.msg)
    // 存token
    setToken(res.token.token)
    const token = res.token.token
    const user = res.user
    const avatar = res.user.avatar
    const name = res.user.name
    setUserName(res.user.name)
    console.log(res)
    context.commit('setToken', token)
    context.commit('setUserInfo', { user, name, avatar })
    // 跳转页面
    router.push('/')
    // token提交本地存储
  },
  // async actionsUserMenus({ commit }) {
  //   const res = await getUserAPI()
  //   commit('mutationsUserMenus', res.data.data)
  // }
  logout(context) {
    context.commit('setToken', '')
    removeToken()
    context.commit('setUserInfo', {})
    resetRouter()// 重置路由
  }
}

export default {
  // 开启命名空间
  namespaced: true,
  state,
  mutations,
  actions
}

